const express = require('express');
const router = express.Router();
const { User, Course, Category } = require('../models');
const { Op } = require('sequelize');
const { success, failure } = require('../utils/responses');
const { getKey, setKey } = require('../utils/redis');
const logger = require('../utils/logger');

/**
 * 查询首页数据
 *
 * GET /admin/auth/sign_in
 * */

router.get('/', async function (req, res) {
  try {
    let data = await getKey('index');
    if (data) {
      return success(res, '查询redis首页数据成功', data);
    }

    const [recommendedCourses, likesCourses, introductoryCourses] = await Promise.all([
      // 推荐课程
      Course.findAll({
        attributes: { exclude: ['CategoryId', 'UserId', 'content'] },
        include: [
          {
            model: Category,
            as: 'category',
            attributes: ['id', 'name'],
          },
          {
            model: User,
            as: 'user',
            attributes: ['id', 'username', 'nickname', 'avatar', 'company'],
          },
        ],
        where: { recommended: true },
        order: [['id', 'desc']],
        limit: 10,
      }),

      Course.findAll({
        attributes: { exclude: ['CategoryId', 'UserId', 'content'] },
        order: [
          ['likesCount', 'desc'],
          ['id', 'desc'],
        ],
        limit: 10,
      }),

      Course.findAll({
        attributes: { exclude: ['CategoryId', 'UserId', 'content'] },
        where: { introductory: true },
        order: [['id', 'desc']],
        limit: 10,
      }),
    ]);
    const _data = {
      recommendedCourses,
      likesCourses,
      introductoryCourses,
    };
    await setKey('index', data, 10);
    success(res, '查询成功', {
      recommendedCourses,
      likesCourses,
      introductoryCourses,
    });
  } catch (error) {
    failure(res, error);
  }
});

module.exports = router;
